HackerRank Beautiful Pairs
提出
2/8 test cases failed :(
code: python
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'beautifulPairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY A
# 2. INTEGER_ARRAY B
#
def beautifulPairs(A, B):
# Write your code here
ans = 0
for i in A:
if i in B:
ans += 1
B.remove(i)
if (ans == n):
return ans
else:
if (len(B) > 0):
return ans + 1
else:
return ans
if __name__ == '__main__':
n = int(input().strip())
A = list(map(int, input().rstrip().split()))
B = list(map(int, input().rstrip().split()))
result = beautifulPairs(A, B)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'beautifulPairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY A
# 2. INTEGER_ARRAY B
#
def beautifulPairs(A, B):
# Write your code here
a = Counter(A)
b = Counter(B)
b_set = 0
for val in a:
if val in b:
# corner case
# must change 1 element
# 1 1 1 - A
# 1 1 1 - B
if b_set == len(A):
return b_set - 1
else:
return b_set + 1
if __name__ == '__main__':
n = int(input().strip())
A = list(map(int, input().rstrip().split()))
B = list(map(int, input().rstrip().split()))
result = beautifulPairs(A, B)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=yKNhg5vWqKY
提出
2/8 test cases failed :(
code: python
import math
import os
import random
import re
import sys
import collections
#
# Complete the 'beautifulPairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY A
# 2. INTEGER_ARRAY B
#
def beautifulPairs(A, B):
# Write your code here
# print(set(A) & set(B))
# print(collections.Counter(A), collections.Counter(B))
# Counter({1: 1, 2: 1, 3: 1, 4: 1}) Counter({3: 2, 1: 1, 2: 1})
AC = collections.Counter(A)
BC = collections.Counter(B)
ans = 0
for v in BC:
else:
restA = set()
restB = set()
for v in AC:
restA.add(v)
for v in BC:
restB.add(v)
if len(restA) > 0 and len(restB) > 0 and len(restA - restB) > 0:
ans += 1
return ans
if __name__ == '__main__':
n = int(input().strip())
A = list(map(int, input().rstrip().split()))
B = list(map(int, input().rstrip().split()))
result = beautifulPairs(A, B)
fptr.write(str(result) + '\n')
fptr.close()